package com.example.demo.service;

import com.example.demo.dto.TableFieldDto;
import com.example.demo.mapper.BaseMapper;
import com.example.demo.util.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * @author caitao
 * @date 2022/2/23 1:16 下午
 * @Description
 */
@Service
public class BaseService {

    @Autowired
    protected BaseMapper baseMapper;

    private String tableName;

    public void setTableName(String tableName) {
        this.tableName = tableName;
    }

    /**
     * 新建表
     * @param cloums
     */
    public void createTable(List<TableFieldDto> cloums){
        this.baseMapper.createTable(this.tableName,cloums);
    }

    /**
     * 插入表数据
     * @param map
     * @return
     */
    public int insert(Map<String,Object> map){
        if(!map.containsKey("id")){
            map.put("id", UUID.randomUUID().toString().replace("-",""));
        }
        map.put("create_by","admin"); //TODO
        map.put("create_date",new Date());
        return this.baseMapper.insert(this.tableName,map);
    }

    /**
     * 根据主键更新表
     * @param map
     * @return
     */
    public int updateByPrimaryKey(Map<String,Object> map){
        if(!map.containsKey("id")){
            throw new RuntimeException("主键id不能为空");
        }
        map.put("last_update_by","admin"); //TODO
        map.put("last_update_date",new Date());
        return this.baseMapper.updateByPrimaryKey(this.tableName,map);
    }

    /**
     * 查询 返回一条
     * @param queryWrapper
     * @return
     */
    public Map<String,Object> selectOne(QueryWrapper queryWrapper){
        return this.baseMapper.selectOne(this.tableName,queryWrapper);
    }

    /**
     * 查询列表
     * @param queryWrapper
     * @return
     */
    public List<Map<String,Object>> selectList(QueryWrapper queryWrapper){
        return this.baseMapper.selectList(this.tableName,queryWrapper);
    }

    /**
     * 判断表是否存在
     * @return
     */
    public int existTable(){
        return this.baseMapper.existTable(this.tableName);
    }

    /**
     * 删除表格
     * @return
     */
    public int dropTable(){
        return this.baseMapper.dropTable(this.tableName);
    }

    /**
     * 根据id删除数据
     * @return
     */
    public int removeById(String id){
        Assert.notNull(id,"主键不能为空");
        return this.baseMapper.removeById(this.tableName,id);
    }

    /**
     * 清空表数据
     * @return
     */
    public int clearTable(){
        return this.baseMapper.clearTable(this.tableName);
    }

}
